package cn.workreport.modules.report.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.workreport.modules.common.vo.PageVO;
import cn.workreport.modules.group.entity.Group;
import cn.workreport.modules.group.service.impl.GroupServiceImpl;
import cn.workreport.modules.message.entity.Message;
import cn.workreport.modules.message.enums.MessageTypeEnum;
import cn.workreport.modules.message.service.IMessageService;
import cn.workreport.modules.report.entity.ReportCommit;
import cn.workreport.modules.report.entity.ReportEntity;
import cn.workreport.modules.report.mapper.ReportCommitMapper;
import cn.workreport.modules.report.service.IReportCommitService;
import cn.workreport.modules.users.entity.UserEntity;
import cn.workreport.modules.users.service.impl.UserServiceImp;
import cn.workreport.util.JsonResult;
import cn.workreport.util.UserChacheFromToken;
import cn.workreport.ws.service.impl.WsMessageServiceImpl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 日报提交记录 业务接口实现类
 * </p>
 *
 * @author yyf
 * @since 2022-02-25
 */
@Slf4j
@Service
public class ReportCommitServiceImpl extends ServiceImpl<ReportCommitMapper, ReportCommit> implements IReportCommitService {

    @Autowired
    private ReportServiceImpl reportService;

    @Autowired
    private UserServiceImp userService;

    @Autowired
    private GroupServiceImpl groupService;

    @Autowired
    private IMessageService messageService;

    @Override
    public void wrapEntity(ReportCommit entity) {

    }

    @Override
    public PageVO<ReportCommit> pageEntity(IPage<ReportCommit> page, Wrapper<ReportCommit> queryWrapper) {
        IPage<ReportCommit> pageResult = this.page(page, queryWrapper);
        return new PageVO<>(pageResult);
    }

    @Override
    public ReportCommit getByIdEntity(Integer id) {
        return null;
    }

    @Override
    public JsonResult<?> saveOrUpdateEntity(ReportCommit entity) {
        if (ObjectUtil.isEmpty(entity.getTodayPlanReportList())) {
            return JsonResult.fail("参数 todayPlanReportList 不能为空");
        }
        // 查询今日有无提交记录
        UserEntity currentLoginUser = UserChacheFromToken.getUser();
        int todayCommitCount = getTodayCommitCountByUserId(currentLoginUser.getId());
        if (todayCommitCount > 0) {
            return JsonResult.fail("你今天已经提交过了");
        }
        // 清除 null 值，保证返回前端的是数组类型
        if (ObjectUtil.isEmpty(entity.getLastFinishReportList())) {
            entity.setLastFinishReportList(new ArrayList<>());
        }
        if (!this.saveOrUpdate(entity)) {
            return JsonResult.fail("操作失败");
        }
        // 发送消息给当前用户的组长
        Message message = new Message();
        message.setType(MessageTypeEnum.DAY_REPORT_MSG);
        String currentLoginUserName = ObjectUtil.isEmpty(currentLoginUser.getTruename()) ? currentLoginUser.getNickname() : currentLoginUser.getTruename();
        message.setTitle(currentLoginUserName + "给您发送了今天的日报");
        sendMessageToLeader(message);
        return JsonResult.ok();
    }

    @Override
    public JsonResult<?> removeByIdEntity(Integer id) {
        boolean isSuccess = super.removeById(id);
        if (!isSuccess) {
            return JsonResult.fail();
        }
        // 发送消息给当前用户的组长
        UserEntity currentLoginUser = UserChacheFromToken.getUser();
        Message message = new Message();
        message.setType(MessageTypeEnum.DAY_REPORT_MSG);
        String currentLoginUserName = ObjectUtil.isEmpty(currentLoginUser.getTruename()) ? currentLoginUser.getNickname() : currentLoginUser.getTruename();
        message.setTitle(currentLoginUserName + "撤回了今天的日报");
        sendMessageToLeader(message);
        return JsonResult.ok();
    }

    @Override
    public JsonResult<?> removeByIdsEntity(List<Integer> ids) {
        for (Integer id : ids) {
            JsonResult<?> jsonResult = removeByIdEntity(id);
            if (!jsonResult.getState().equals(JsonResult.SUCCESS)) {
                return JsonResult.fail();
            }
        }
        return JsonResult.ok();
    }

    @Override
    public JsonResult<?> sendTodayReport(List<Integer> lastFinishReportIds, List<Integer> todayPlanReportIds, String reportCommitRemark) {
        if (ObjectUtil.isEmpty(todayPlanReportIds)) {
            return JsonResult.fail("缺少参数 todayPlanReportIds");
        }
        // 查询今日有无提交记录
        UserEntity currentLoginUser = UserChacheFromToken.getUser();
        int todayCommitCount = getTodayCommitCountByUserId(currentLoginUser.getId());
        if (todayCommitCount > 0) {
            return JsonResult.fail("你今天已经提交过了");
        }
        ReportCommit reportCommitEntity = new ReportCommit();

        if (ObjectUtil.isEmpty(lastFinishReportIds)) {
            reportCommitEntity.setLastFinishReportList(new ArrayList<>());
        } else {
            List<ReportEntity> lastFinishReportList = reportService.listByIds(lastFinishReportIds);
            if (ObjectUtil.isEmpty(lastFinishReportList)) {
                lastFinishReportList = new ArrayList<>();
            }
            reportCommitEntity.setLastFinishReportList(lastFinishReportList);
        }

        List<ReportEntity> todayPlanReportList = reportService.listByIds(todayPlanReportIds);
        if (ObjectUtil.isEmpty(todayPlanReportList)) {
            todayPlanReportList = new ArrayList<>();
        }
        reportCommitEntity.setTodayPlanReportList(todayPlanReportList);
        reportCommitEntity.setReportCommitRemark(reportCommitRemark);
        log.info("reportCommitEntity =" + reportCommitEntity);
        boolean isSuccess = super.saveOrUpdate(reportCommitEntity);
        if (!isSuccess) {
            return JsonResult.fail("操作失败");
        }
        // 发送消息给当前用户的组长
        Message message = new Message();
        message.setType(MessageTypeEnum.DAY_REPORT_MSG);
        String currentLoginUserName = ObjectUtil.isEmpty(currentLoginUser.getTruename()) ? currentLoginUser.getNickname() : currentLoginUser.getTruename();
        message.setTitle(currentLoginUserName + "给您发送了今天的日报");
        sendMessageToLeader(message);
        return JsonResult.ok();
    }

    @Override
    public JsonResult<?> getCommitCountSelf() {
        // 查询今日有无提交记录
        UserEntity currentLoginUser = UserChacheFromToken.getUser();
        int todayCommitCount = getTodayCommitCountByUserId(currentLoginUser.getId());
        return JsonResult.ok(todayCommitCount);
    }

    /**
     * 查找某个用户今天提交的数量
     *
     * @param userId 用户id
     * @return 数量
     */
    public int getTodayCommitCountByUserId(Integer userId) {
        if (ObjectUtil.isEmpty(userId)) {
            return 0;
        }
        LambdaQueryWrapper<ReportCommit> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ReportCommit::getCreatorId, userId);
        wrapper.ge(ReportCommit::getCreatedTime, DateUtil.beginOfDay(new Date()));
        wrapper.le(ReportCommit::getCreatedTime, DateUtil.endOfDay(new Date()));
        return count(wrapper);
    }

    /**
     * 查找某个用户今天提交的数量
     *
     * @param userId 用户id
     * @return 数量
     */
    public List<ReportCommit> listByUserId(Integer userId, Date startCreatedTime, Date endCreatedTime) {
        if (ObjectUtil.isEmpty(userId)) {
            return null;
        }
        LambdaQueryWrapper<ReportCommit> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ReportCommit::getCreatorId, userId);
        wrapper.ge(ObjectUtil.isNotNull(startCreatedTime), ReportCommit::getCreatedTime, startCreatedTime);
        wrapper.lt(ObjectUtil.isNotNull(endCreatedTime), ReportCommit::getCreatedTime, endCreatedTime);
        return list(wrapper);
    }

    /**
     * 发送消息给当前登录用户的组长（如果自己是组长，则发给上级的组长）
     *
     * @param message
     */
    public void sendMessageToLeader(Message message) {
        UserEntity currentLoginUser = UserChacheFromToken.getUser();
        // 如果当前用户是有组织的
        if (!ObjectUtil.isEmpty(currentLoginUser.getGroupId())) {
            UserEntity leader = null;
            // 如果当前用户是组长，发消息给他上一级的组长
            if (!ObjectUtil.isEmpty(currentLoginUser.getIsLeader()) && currentLoginUser.getIsLeader()) {
                Group currentGroup = groupService.getById(currentLoginUser.getGroupId());
                if (!ObjectUtil.isEmpty(currentGroup) && !ObjectUtil.isEmpty(currentGroup.getParentId())) {
                    leader = userService.getLeaderByGroupId(currentGroup.getParentId());
                }
            } else {
                // 调用convertAndSendToUser来推送消息给当前用户的组长
                leader = userService.getLeaderByGroupId(currentLoginUser.getGroupId());
            }
            if (!ObjectUtil.isEmpty(leader)) {
                messageService.sendMsgToUser(leader.getId(), message);
            }
        }
    }
}

